﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Input;
using Security.Domain;
using Security.Events;
using Security.Events.Commands;
using Security.Helpers;
using Security.Specs.DataLayer;
using Security.Specs.Implementation.Common;
using Security.Specs.Reports;

namespace Security.Specs.Implementation.NodeRoots
{
    [Export(typeof(SecurityNodeReportBase)), SecurityNodeRootMetadata(typeof(ServerLogin), (int)SecurityRootNodeOrder.Logins)]
    public class ServerLoginSecurityNodeRoot : SecurityNodeReport
    {
        private readonly EventBroker eventBroker;
        private readonly ISecurityDataModel model;

        [ImportingConstructor]
        public ServerLoginSecurityNodeRoot(EventBroker eventBroker, ISecurityDataModel model) :
            base(Strings.GetRootNodeDescription(typeof(ServerLogin)), typeof(ServerLogin))
        {
            this.eventBroker = eventBroker;
            this.model = model;

            nodes.Add(Empty());

            Subscribe();
        }

        private void Subscribe()
        {
            eventBroker.OfType<ChangesCommittedCommand>().
                Where(c => c.Type.IsBaseOf(typeof(ServerLogin))).
                Subscribe(OnChangesCommited);
        }

        private void OnChangesCommited(ChangesCommittedCommand command)
        {
            ChildNodesCollectionNeeded();
        }

        protected override void ChildNodesCollectionNeeded()
        {
           
                nodes.Clear();
                foreach (var serverLogin in model.ServerLogins.OrderBy(l => l.Name).ToArray())
                {
                    nodes.Add(new SecurityNodeReport(serverLogin.Name, serverLogin));
                }
            
        }
    }
}